#!/usr/bin/env python

import urllib2

import sqlalchemy as sa
import sqlalchemy.orm as sao

import _base as base

from datetime import datetime
from model import DeclarativeBase

__all__ = ['Booru']

class Booru(DeclarativeBase):
    """Booru class"""
    
    __tablename__ = 'boorus'
    
    id = sa.Column(sa.Integer, primary_key=True)
    md5 = sa.Column(sa.String(32), sa.ForeignKey('posts.md5'), nullable=False,
                    index=True)
    hostId = sa.Column(sa.Integer, sa.ForeignKey('hosts.id'), nullable=False,
                       index=True)
    originalId = sa.Column(sa.Integer, nullable=False, index=True)
    url = sa.Column(sa.Text)
    dateTime = sa.Column(sa.DateTime)
    createdAt = sa.Column(sa.DateTime, default=datetime.now)
    updatedAt = sa.Column(sa.DateTime, default=datetime.now,
                          onupdate=datetime.now)
    host = sao.relationship('Host', uselist=False)
    post = sao.relationship('Post', uselist=False)
    
    def download(self, reportHook=None):
        """Download image file form booru.
        
        Args:
            reportHook: A function that will be call periodically when download
                is in progress. The function must have two arguments of total
                and progress.
        """
        counter = 0
        block = 1024
        tempFile = open(self.post.temp.path, 'wb')
        
        url = self.url
        if url[0:4].lower() != 'http': url = '%s%s' % (self.host.url, self.url) 
        request = urllib2.Request(url)
        request.add_header('Referer', self.host.url)
        
        url = urllib2.urlopen(request, timeout=30)
        meta = url.info()
        if meta.has_key('Content-Length'):
            size = long(meta.getheader('Content-Length'))
        
        if reportHook: reportHook(size, 1)
        
        for chunk in iter(lambda: url.read(block), ''):
            counter += 1
            tempFile.write(chunk)
            if reportHook: reportHook(size, counter * block)
            
        tempFile.close()
        
        return True
